package wjh.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import wjh.config.AlipayConfig;
import wjh.pojo.Doctor;
import wjh.pojo.ExamForm;
import wjh.pojo.Notice;
import wjh.pojo.Patient;
import wjh.service.*;
import wjh.utils.AlipayUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/examForm")
public class ZlyExamFormController {
    @Autowired
    private ZlyExamFormService zlyExamFormService;

    @Autowired
    private ZlyDepartmentService zlyDepartmentService;

    @Autowired
    private ZlyDoctorService zlyDoctorService;

    @Autowired
    private ZlyPatientService zlyPatientService;

    @Autowired
    private RegisterService registerService;

    private List<String> deptNameList = new ArrayList<>();
    private String newPid;
    private String report_number = "";
    @PostMapping("/appoForm")
    public ModelAndView checkForm(@RequestParam List<Integer> did, @RequestParam String pname, @RequestParam("id") Integer pid) {
        deptNameList.clear();
        report_number = String.valueOf(System.currentTimeMillis());
        Timestamp date = new Timestamp(new Date().getTime());
        int money = 0;
        for (Integer id : did){
//            查询id对应科室名称
            String deptName = zlyDepartmentService.findById(id);
            deptNameList.add(deptName);
            money++;
        }

//        创建ExamForm对象并保存
        ExamForm examForm = new ExamForm(null, pname, report_number, date.toString(), deptNameList.toString(), "体检结果：", "-1");
        zlyExamFormService.saveForm(examForm, money);
        Patient patient = registerService.findPatientById(pid);
        ModelAndView modelAndView = new ModelAndView("checkForm");
        modelAndView.addObject("patient", patient);
        modelAndView.addObject("deptNameList", deptNameList);
        modelAndView.addObject("examForm", examForm);
        modelAndView.addObject("money", money);
        return modelAndView;
    }

    @RequestMapping ("/succ")
    public String succ(@RequestParam String pid ,@RequestParam String report_number,
                       @RequestParam String money, HttpServletResponse response) {
        newPid = pid;
        return AlipayUtil.confirmPayment(report_number,money,"体检","体检",response);
    }
    @RequestMapping(value = "/alipayReturnNotice")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        System.out.println("支付成功, 进入同步通知接口...");
        Notice notice = AlipayUtil.checkSign(request);
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (notice.isSignVerified()) {
            // 修改订单状态，改为 支付成功
            for (String dept : deptNameList) {
                Doctor doctor = zlyDoctorService.findByDept(dept);
                zlyExamFormService.saveExamtoDoct(report_number, Integer.valueOf(newPid), doctor.getId());
            }
            int status = 0;
            zlyExamFormService.changeState(report_number, status);
            System.out.println("********************** 支付成功(支付宝同步通知) **********************");
            System.out.println(notice);
            System.out.println("***************************************************************");
        } else {
            System.out.println("支付, 验签失败...");
        }
        return notice.getModelAndView();
    }
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        System.out.println("支付成功, 进入异步通知接口...");
        Notice notice = AlipayUtil.checkSign(request);
		//实际验证过程建议务必添加订单号、实际支付金额、商户操作、APPID校验：
        if (notice.isSignVerified()) {//验证成功
            if (notice.getTradeStatus().equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果有做过处理，不执行商户的业务程序
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (notice.getTradeStatus().equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                System.out.println("********************** 支付成功(支付宝异步通知) **********************");
                System.out.println(notice);
                System.out.println("***************************************************************");
            }
            System.out.println("支付成功...");
        } else {//验证失败
            System.out.println("支付, 验签失败...");
        }
        return "succ";
    }

    @PostMapping("/subExam")
    public ModelAndView subExam(@RequestParam String subExam, @RequestParam String rNumber, @RequestParam int did){
        zlyExamFormService.subExam(subExam, rNumber);
        zlyExamFormService.delRUD(rNumber, did);
        Object count = zlyExamFormService.checkReportDone(rNumber);
        if (count == null){
            zlyExamFormService.changeState(rNumber, 1);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/doctor/docexam.do");
        return modelAndView;
    }

    @RequestMapping("/detail")
    public ModelAndView detail(@RequestParam String rNumber){
        ExamForm examForm = zlyExamFormService.findByReportNumber(rNumber);
        ModelAndView modelAndView = new ModelAndView("detail");
        modelAndView.addObject("examForm", examForm);
        return modelAndView;
    }
    @RequestMapping("/remove")
    public ModelAndView  remove(@RequestParam String rNumber, @RequestParam Integer id){
        zlyExamFormService.changeState(rNumber, -2);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject(id);
        modelAndView.setViewName("redirect:/patient/history.do?id="+id);
        return modelAndView;
    }
}
